parasails.registerPage('welcome', {
  //  ╦╔╗╔╦╔╦╗╦╔═╗╦    ╔═╗╔╦╗╔═╗╔╦╗╔═╗
  //  ║║║║║ ║ ║╠═╣║    ╚═╗ ║ ╠═╣ ║ ║╣
  //  ╩╝╚╝╩ ╩ ╩╩ ╩╩═╝  ╚═╝ ╩ ╩ ╩ ╩ ╚═╝
  data: {
    modal: '',
    backgroundColors: [ // Chart Colors
      '#E07A83',  // Critical severity (red)
      '#FB8B62', // High severity (orange)
      '#F5B868', // Medium severity (yellow)
      '#CBE7A5', // Low severity (green)
      '#D9D9D9' // Unknown severity (grey)
    ],
    borderColors: [ // Chart border colors
      '#8C323A',  // Critical severity (red)
      '#E75D29', // High severity (orange)
      '#C98328', // Medium severity (yellow)
      '#99B179', // Low severity (green)
      '#AFAFAF' // Unknown severity (grey)
    ],
    dataForGraphs: {},
    vulnBySeverityDataset: {},
    priorityVulnPatchProgress: [],
    cloudError: '',
    syncingMessage: '',
    syncing: false,
    graphSyncing: true,
    formData: {
      priorityCves: [],
    },
    formErrors: {},
    formRules: {},
  },

  //  ╦  ╦╔═╗╔═╗╔═╗╦ ╦╔═╗╦  ╔═╗
  //  ║  ║╠╣ ║╣ ║  ╚╦╝║  ║  ║╣
  //  ╩═╝╩╚  ╚═╝╚═╝ ╩ ╚═╝╩═╝╚═╝
  beforeMount: function() {
    this.dataForGraphs = this.realDataForGraphs;
  },
  mounted: async function() {
    await this.getPriorityCves();
    await this.getDataForGraphs();


  },

  //  ╦╔╗╔╔╦╗╔═╗╦═╗╔═╗╔═╗╔╦╗╦╔═╗╔╗╔╔═╗
  //  ║║║║ ║ ║╣ ╠╦╝╠═╣║   ║ ║║ ║║║║╚═╗
  //  ╩╝╚╝ ╩ ╚═╝╩╚═╩ ╩╚═╝ ╩ ╩╚═╝╝╚╝╚═╝
  methods: {
    clickOpenEditModal: function () {
      this.formData.priorityCves = _.pluck(this.priorityVulnPatchProgress, 'cveId');
      this.modal = 'priority-cves';
    },
    handleSubmittingPriorityCveForm: async function(argins) {
      this.syncing = true;
      this.syncingMessage = 'Updating priority vulnerabilities...';
      let newVulnPatchProgress = await Cloud.updatePriorityVulnerabilities.with({newPriorityCveIds: argins.priorityCves}).tolerate('invalidCve', (err)=>{
        this.cloudError = err;
      });
      this.syncing = false;
      if(!this.cloudError){
        this.priorityVulnPatchProgress = newVulnPatchProgress;
        this.modal = '';
      }
      await this.forceRender();

    },
    clickCloseModal: async function () {
      this.formData = {};
      this.cloudError = '';
      this.syncing = false;
      this.modal = '';
    },
    getPriorityCves: async function () {
      this.syncing = true;
      let priorityCveProgress = await Cloud.getPriorityVulnerabilities();
      this.priorityVulnPatchProgress = priorityCveProgress;
      this.syncing = false;
    },
    getDataForGraphs: async function () {
      this.graphSyncing = true;
      this.dataForGraphs = await Cloud.getDashboardGraphData();
      this.vulnBySeverityDataset = {
        labels: ['Critical', 'High', 'Medium', 'Low', 'Unknown'],
        datasets: [{
          backgroundColor: this.backgroundColors,
          borderColor: this.borderColors,
          borderWidth: 1,
          pointRadius: 0,
          data: this.dataForGraphs.numberOfVulnsBySeverity,
        }]
      };
      this.graphSyncing = false;
      await this.drawGraphsOnPage();
    },
    drawGraphsOnPage: async function(){
      new Chart('average-remediation-time', {
        type: 'line',
        data: {
          datasets: [
            {
              backgroundColor: ['#BEC2DE'],
              borderColor: '#8C93C0',
              borderWidth: 1,
              tension: 0,
              label: 'Average number of days to resolve critical vulnerabilities',
              data: _.filter(this.dataForGraphs.remediationTimeline, (graphPoint)=>{// Future: Revert this change and do this in view-welcome.js
                return graphPoint.y !== 'N/A';
              })
            },
          ]
        },
        options: {
          title: {
            display: false,
            text: 'Average remediation time in days',
          },
          legend:{
            display: false,
          },
          tooltips: {
            mode: 'nearest',
            intersect: false
          },
          scales: {
            xAxes: [{
              type: 'time',
              time: {
                unit: 'week'
              }
            }]
          }
        }
      });
      new Chart('percent-with-critical-vulns', {
        type: 'doughnut',
        data: {
          labels: ['Critical', 'None'],
          datasets: [{
            label: 'percent',
            data: this.dataForGraphs.criticalVulnerabilityPercentage,
            backgroundColor: ['#E07A83','#BEC2DE'],
            borderColor: ['#E07A83','#8C93C0'],
            borderWidth: 1,
          }]
        },
        options: {
          aspectRatio: 1,
          title: {
            display: false,
            text: 'Percent of Hosts with vulnerabilities',
          },
          legend: {
            labels: {
              generateLabels: (chart) => {
                const datasets = chart.data.datasets;
                return datasets[0].data.map((data, i) => ({
                  text: `${chart.data.labels[i]} (${data}%)`,
                  fillStyle: datasets[0].backgroundColor[i],
                  pointStyle: 'rectRounded',
                  lineWidth: 0,
                }));
              },
              boxWidth: 15,
              boxHeight: 24,
              padding: 20,
              fontSize: 14,
            },
          },
        },
      });
      new Chart('percent-with-high-vulns', {
        type: 'doughnut',
        data: {
          labels: ['High', 'None'],
          datasets: [{
            label: 'percent',
            data: this.dataForGraphs.highVulnerabilityPercentage,
            backgroundColor: ['#FB8B62','#BEC2DE'],
            borderColor: ['#E07A83','#8C93C0'],
            borderWidth: 1,
          }]
        },
        options: {
          aspectRatio: 1,
          title: {
            display: false,
            text: 'Percent of Hosts with vulnerabilities',
          },
          legend: {
            labels: {
              generateLabels: (chart) => {
                const datasets = chart.data.datasets;
                return datasets[0].data.map((data, i) => ({
                  text: `${chart.data.labels[i]} (${data}%)`,
                  fillStyle: datasets[0].backgroundColor[i],
                  pointStyle: 'rectRounded',
                  lineWidth: 0,
                }));
              },
              boxWidth: 15,
              boxHeight: 24,
              padding: 20,
              fontSize: 14,
            },
          },
        },
      });
      new Chart('vuln-by-severity', {
        type: 'bar',
        data: this.vulnBySeverityDataset,
        options: {
          title: {
            display: false,
            text: 'Number of Hosts with vulnerabilities by severity',
          },
          interaction: {
            mode: 'x'
          },
          tooltips: {
            mode: 'nearest',
            intersect: false
          },
          legend: {
            display: false,
          },
          scales: {
            y: {
              beginAtZero: true,
            }
          },
          onClick: (event, elements)=> {
            if (elements.length > 0) {
              const index = elements[0]._index;
              const value = this.vulnBySeverityDataset.labels[index];
              // Use the value to navigate to a different page or display information
              if(value === 'Critical'){
                window.location = '/vulnerability-list?minSeverity=9';
              } else if(value === 'High'){
                window.location = '/vulnerability-list?minSeverity=7&maxSeverity=8.9';
              } else if(value === 'Medium'){
                window.location = '/vulnerability-list?minSeverity=4.0&maxSeverity=6.9';
              } else if(value === 'Low'){
                window.location = '/vulnerability-list?minSeverity=0.1&maxSeverity=3.9';
              } else if(value === 'Unknown'){
                window.location = '/vulnerability-list?minSeverity=0&maxSeverity=0';
              }
            }
          }
        },
      });
      new Chart('vuln-over-time', {
        type: 'line',
        data: {
          datasets: [
            {
              label: 'Critical',
              backgroundColor: '#E07A83',
              borderColor: '#8C323A',
              borderWidth: 1,
              fill: 'origin',
              tension: 0,
              order: 2,
              data: this.dataForGraphs.timelineDatasets.critical
            },
            {
              label: 'High',
              backgroundColor: '#FB8B62',
              borderColor: '#E75D29',
              borderWidth: 1,
              fill: 'origin',
              tension: 0,
              order: 3,
              data: this.dataForGraphs.timelineDatasets.high
            },
            {
              label: 'Medium',
              backgroundColor: '#F5B868',
              borderColor: '#C98328',
              borderWidth: 1,
              fill: 'origin',
              tension: 0,
              order: 5,
              data: this.dataForGraphs.timelineDatasets.medium
            },
            {
              label: 'Low',
              backgroundColor: '#CAE6A5',
              borderColor: '#99B179',
              borderWidth: 1,
              fill: 'origin',
              tension: 0,
              order: 4,
              data: this.dataForGraphs.timelineDatasets.low
            },
            {
              label: 'Unknown',
              backgroundColor: '#D9D9D9',
              borderColor: '#AFAFAF',
              borderWidth: 1,
              fill: 'origin',
              tension: 0,
              order: 1,
              data: this.dataForGraphs.timelineDatasets.unknown
            },
          ]
        },
        options: {
          title: {
            display: false,
            text: 'Number of vulnerabilities detected by severity',
          },
          tooltips: {
            mode: 'nearest',
            intersect: false
          },
          legend: {
            reverse: true,
            labels: {
              boxWidth: 15,
              boxHeight: 24,
              padding: 20,
              fontSize: 14,
            },
          },
          scales: {
            y: {
              beginAtZero: true
            },
            xAxes: [{
              type: 'time',
              time: {
                unit: 'week'
              }
            }]
          }
        },
      });
    }

  }
});
